package captcha.demos;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    public Captcha captchaProperties ;
    private int VALID_TIME=60*1000;//1min

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletRequest request,HttpServletResponse response){

        try {
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Pragma", "No-cache");
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties .getWidth(), captchaProperties .getHeight());
            HttpSession session = request.getSession();
            session.setAttribute(captchaProperties .getSession().getKey(), lineCaptcha.getCode());
            session.setAttribute(captchaProperties .getSession().getDate(), new Date());
            lineCaptcha.write(response.getOutputStream());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @RequestMapping("/check")
    public Boolean check(String captcha,HttpSession session){
        if(!StringUtils.hasLength(captcha))
        return false;
       String code=(String)session.getAttribute(captchaProperties .getSession().getKey());
       Date date=(Date)session.getAttribute(captchaProperties .getSession().getDate());
       if(captcha.equalsIgnoreCase(code)&&System.currentTimeMillis()-date.getTime()<VALID_TIME)
           return true;
       return false;
    }


}
